#include "head.h"
#include <sys/wait.h>
#include <stdlib.h>

int main(int argc, char **argv) {
    int opt;
    int fd;
    int start, end;
    char buff[1024];
    pid_t pid;
    int waitCnt = 0;
    int sum = 0;
    while ((opt = getopt(argc, argv, "s:e:")) != -1) {
        switch (opt) {
            case 's':
                start = atoi(optarg);
                // printf("s : %d\n", start);
                break;
            case 'e':
                end = atoi(optarg);
                // printf("e : %d\n", end);
                break;
            default:
                printf("error\n");
                break;
        }
    }
    if ((fd = open("./add.txt", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) < 0) {
        perror("open()");
        exit(1);
    }
    memset(buff, 0, sizeof(buff));
    sprintf(buff, "%d,%d", start, start + 1);
    write(fd, buff, sizeof(buff));
    close(fd);

    if ((pid = fork()) < 0) {
            perror("fork()");
            exit(1);
        }
    if (pid == 0) {
        printf("Child Process\n");
        int a, b;
        if ((fd = open("./add.txt", O_RDWR)) < 0) {
            perror("open()");
            exit(1);
            // continue;
        }
        memset(buff, 0, sizeof(buff));
        if (flock(fd, LOCK_EX) == -1) {
            perror("flock(LOCK_EX)");
            exit(1);
        }
        if (read(fd, buff, sizeof(buff)) > 0) {
            if (strcmp(buff, "end") == 0) {
                close(fd);
                exit(0);
            } else {
                sscanf(buff, "%d,%d", &a, &b); 
            }
        }
        sum = a + b;
        if (b == end) {
            // printf("end\n");
            strcpy(buff, "end");
        } else {
            // printf("%d\n", sum);
            sprintf(buff, "%d,%d", sum, b + 1);
        }
        lseek(fd, 0, SEEK_SET);
        if (write(fd, buff, sizeof(buff)) < 0) {
            perror("write()");
            exit(1);
        }
        if (flock(fd, LOCK_UN) < 0) {
            perror("flock(LOCK_UN)");
            exit(1);
        }
        close(fd);
    } else {
        wait(NULL);
        // sleep(5);
        if ((fd = open("./add.txt", O_RDWR)) < 0) {
            perror("open()");
            exit(1);
        }
        memset(buff, 0, sizeof(buff));
        if (read(fd, buff, sizeof(buff)) > 0) {
            printf("%s\n", buff);
        }
        // printf("%d\n", sum);
    }

    return 0;
}